package com.wpw.dream.http.util;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtil {

	private CloseableHttpClient client;
	private HttpRequestBase request;
	private Builder configBuilder;
	private URIBuilder uriBuilder;
	private EntityBuilder entityBuilder;
	
	private HttpUtil(HttpRequestBase request) {
		this.request = request;
		this.client = HttpClients.createDefault();
		this.entityBuilder = EntityBuilder.create();
		
	}
	
	private HttpUtil(HttpRequestBase request, HttpUtil httpUtil) {
		this.request = request;
		this.client = httpUtil.client;
		this.configBuilder = httpUtil.configBuilder;
	}

	private static HttpUtil create(HttpRequestBase request) {
		return new HttpUtil(request);
	}

	private static HttpUtil create(HttpRequestBase request, HttpUtil httpUtil) {
		return new HttpUtil(request, httpUtil);
	}
	
	public static HttpUtil post(String url) {
		return create(new HttpPost(url));
	}
	
	public static HttpUtil post(String url, HttpUtil httpUtil) {
		return create(new HttpPost(url), httpUtil);
	}
	
	public void excute() {
		
	}
	
	public HttpUtil addParameter(String name, String value) {
		if (entityBuilder != null) {
			entityBuilder.getParameters().add(new BasicNameValuePair(name, value));
		} else {
			uriBuilder.addParameter(name, value);
		}
		return this;
	}
	
	public HttpUtil setParameters(NameValuePair...parameters) {
		if (entityBuilder != null) {
			entityBuilder.setParameters(parameters);
		} else {
			uriBuilder.setParameters(parameters);
		} 
		return this;
	}
	
	public HttpUtil setParameters(Map<String, String> parameters) {
		NameValuePair [] values = new NameValuePair[parameters.size()];
		int i = 0;
		
		for (Entry<String, String> parameter : parameters.entrySet()) {
			values[i++] = new BasicNameValuePair(parameter.getKey(), parameter.getValue());
		}
		
		setParameters(values);
		return this;
	}



	public static void main(String[] args) {
		HttpUtil post = HttpUtil.post("http://www.baidu.com");
	}
	
}
